<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    width="40%"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicForm, useForm } from '@/components/Form/index';
import { formSchema } from './data';
import { useMessage } from '@/hooks/web/useMessage';
import { add, edit } from '@/api/sys/restManager';
import { useI18n } from '@/hooks/web/useI18n';
const { t } = useI18n();
const emit = defineEmits(['success']);
let isUpdate = ref(true);
const { createMessage } = useMessage();
const [registerForm, { updateSchema, resetFields, setFieldsValue, validate }] =
  useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

const [registerModal, { setModalProps, closeModal }] = useModalInner(
  async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      updateSchema([{ field: 'dbKey', componentProps: { disabled: true } }]);
      setFieldsValue({
        ...data.record,
      });
    }
  }
);
const getTitle = computed(() => (!unref(isUpdate) ? t('新增') : t('编辑')));

async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    if (unref(isUpdate)) {
      await edit('reportDataSource', values);
      createMessage.success(t('修改成功'));
    } else {
      await add('reportDataSource', values);
      createMessage.success(t('保存成功'));
    }
    closeModal();
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
